package com.tju.hotel.hotel.ui;

import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.tju.hotel.hotel.MyApplication;
import com.tju.hotel.R;
import com.tju.hotel.hotel.bean.MemberBean;
import com.tju.hotel.hotel.ui.home.HomeFragment;
import com.tju.hotel.hotel.ui.order.OrderFragment;
import com.tju.hotel.hotel.ui.user.UserFragment;
import com.tju.hotel.hotel.util.MD5Util;
import com.tju.hotel.hotel.util.OkHttpTool;
//import com.tju.hotel.hotel.util.SPUtils;
import com.tju.hotel.hotel.util.SPUtils;
import com.tju.hotel.hotel.util.ServiceUrls;
import com.tju.hotel.hotel.util.Tools;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

public class MainActivity extends AppCompatActivity {

    private  final String TAG="LIFE MainActivity";

    private Activity mActivityContext;
    private MyApplication myApplication;
    private Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create();
    Fragment[] fragments=new Fragment[]{null,null,null};//存放Fragment
    //控件
    private LinearLayout llContent; //内容容器
    private RadioButton rbHome;//rb 主页
    private RadioButton rbOrder;//rb 订单
    private RadioButton rbUser;//rb 用户

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        Log.d(TAG,"onCreate");


        super.onCreate(savedInstanceState);
        mActivityContext=this;
        myApplication= (MyApplication) getApplication();
        setContentView(R.layout.activity_main);

        //获取控件
        llContent = findViewById(R.id.ll_main_content);
        rbHome = findViewById(R.id.rb_main_home);
        rbOrder = findViewById(R.id.rb_main_order);
        rbUser = findViewById(R.id.rb_main_user);

        //页面初始化方法
        initView();

        //设置控件点击事件
        setViewEventListener();

    }

    private void initView() {
        //===默认选中主页
        rbHome.setChecked(true);
        switchFragment(0);//默认显示HomeFragment

        //获取是否已经登录过--如果已经登录就自动登录
        String phone=(String) SPUtils.get(mActivityContext,ServiceUrls.SP_MEMBER_PHONE,"");
        String password= (String) SPUtils.get(mActivityContext,ServiceUrls.SP_MEMBER_PASSWORD,"");
        if (Tools.isNotNull(phone)){
            //==发送请求
            //url
            String url =ServiceUrls.getMemberMethodUrl("loginByPassword");
            //参数
            Map<String, Object> map = new HashMap<>();
            map.put("phone", phone);
            map.put("password", password);
            //发送请求
            OkHttpTool.httpPost(url, map, new OkHttpTool.ResponseCallback() {
                @Override
                public void onResponse(final boolean isSuccess, final int responseCode, final String response, Exception exception) {
                    mActivityContext.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            String strText = "无法访问服务器，请检查网络连接";
                            if (isSuccess && responseCode == 200) {
                                try {
                                    JSONObject jsonObject = new JSONObject(response);
                                    int code = jsonObject.getInt("code");
                                    strText = jsonObject.getString("text");
                                    if (code == 200) {
                                        String strData = jsonObject.getString("data");
                                        MemberBean memberBean = gson.fromJson(strData, MemberBean.class);
                                        if (memberBean != null) {
                                            //将用户信息保存到Application（内存）
                                            myApplication.setLoginMember(memberBean);
                                        }
                                    }
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                            }
                            Toast.makeText(mActivityContext, strText, Toast.LENGTH_LONG).show();
                        }
                    });
                }
            });
        }

    }


    //设置控件点击事件
    private void setViewEventListener() {
        //HomeFragment
        rbHome.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                switchFragment(0);//0-HomeFragment
            }
        });
        //OrderFragment
        rbOrder.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                switchFragment(1);//1-OrderFragment
            }
        });
        //UserFragment
        rbUser.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                switchFragment(2);//2-UserFragment
            }
        });
    }





    /**
     * 方法 - 切换Fragment
     *
     * @param fragmentIndex 要显示Fragment的索引
     */
    private  void switchFragment(int fragmentIndex){

        //在Activity中显示Fragment
        //1、获取Fragment管理器 FragmentManager
        FragmentManager fragmentManager=this.getSupportFragmentManager();
        //2、开启fragment事务
        FragmentTransaction transaction=fragmentManager.beginTransaction();

        //懒加载 - 如果需要显示的Fragment为null，就new。并添加到Fragment事务中
        if (fragments[fragmentIndex]==null){
            switch (fragmentIndex){
                case 0://home
                    fragments[fragmentIndex]=new HomeFragment();
                    break;
                case 1://order
                    fragments[fragmentIndex]=new OrderFragment();
                    break;
                case 2://user
                    fragments[fragmentIndex]=new UserFragment();
                    break;
            }
            //==添加Fragment对象到Fragment事务中
            //参数：显示Fragment的容器的ID，Fragment对象
            transaction.add(R.id.ll_main_content,fragments[fragmentIndex]);
        }

        //隐藏其他的Fragment
        for (int i=0;i<fragments.length;i++){
            if (fragmentIndex!=i && fragments[i]!=null){
                //隐藏指定的Fragment
                transaction.hide(fragments[i]);
            }
        }



        //3、显示Fragment
        transaction.show(fragments[fragmentIndex]);
        //4、提交事务
        transaction.commit();
    }

    @Override
    protected void onStart() {
        super.onStart();
        Log.d(TAG,"onStart");
    }

    @Override
    protected void onResume() {
        super.onResume();
        Log.d(TAG,"onResume");
    }

    @Override
    protected void onPause() {
        super.onPause();
        Log.d(TAG,"onPause");
    }

    @Override
    protected void onStop() {
        super.onStop();
        Log.d(TAG,"onStop");
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        Log.d(TAG,"onRestart");
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.d(TAG,"onDestroy");
    }
}
